//
//  DownLoaderManager.m
//  DownloadManager
//
//  Created by 马滕亚 on 2020/4/15.
//  Copyright © 2020 M.Y.A. All rights reserved.
//

#import "DownLoaderManager.h"
#import "DownLoader.h"

@interface DownLoaderManager ()
/**
 每次实例化一个 DownLoader 对应一个文件的下载操作
 如果才操作没有执行完毕，不需要再次开启
 
 解决方案：下载缓冲池
 */

@property (nonatomic, strong) DownLoader *downLoader;
/** 下载操作的缓冲池 */
@property (nonatomic, strong) NSMutableDictionary *downLoaderCache;

/** 失败回调 */
@property (nonatomic, copy) void(^failedBlock)(NSString *);

@end



@implementation DownLoaderManager

- (NSMutableDictionary *)downLoaderCache {
    if (!_downLoaderCache) {
        _downLoaderCache = [[NSMutableDictionary alloc] init];
    }
    return _downLoaderCache;
}

+ (instancetype)shareDownLoaderManager {
    
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    
    return instance;    
}

// 下载
- (void)downloadWithUrl:(NSURL *)url progress:(void(^)(float progress))progress completion:(void(^)(NSString *filePath))completion faied:(void(^)(NSString *errorMsg))faied {
    self.failedBlock = faied;
    // 1、先判断缓冲池是否存在下载任务
    DownLoader *downLoader = self.downLoaderCache[url.path];
    if (downLoader != nil) {
        NSLog(@"下载操作存在");
        return;
    }
    // 2、创建新的下载任务
    downLoader = [[DownLoader alloc] init];
    // 3、将下载任务保存到缓冲池
    [self.downLoaderCache setObject:downLoader forKey:url.path];
    // 传递block的参数
    [downLoader downloadWithUrl:url progress:progress completion:^(NSString * _Nonnull filePath) {
        // 1、从下载缓存池中删除下载操作
        [self.downLoaderCache removeObjectForKey:url.path];
        // 2、执行调用方传递的block
        if (completion) {
            completion(filePath);
        }
    } faied:faied];
   
//    [downLoader downloadWithUrl:url progress:progress completion:completion faied:faied];
}

// 暂停
 - (void)pauseWithUrl:(NSURL *)url {
     // 通过url获取下载操作
     DownLoader *downLoader = self.downLoaderCache[url.path];
     // 判断该操作是否存在
     if (downLoader == nil) {
         if (self.failedBlock) {
             self.failedBlock(@"暂停操作不存在");
         }
         return;
     }
     // 暂停
     [downLoader pause];
     // 从下载缓存池中移除
     [self.downLoaderCache removeObjectForKey:url.path];
}

@end
